import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.resps.Tuple;

import java.util.List;

public class RedisZSetDemo {
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.flushAll();
//            test1(jedis);
//            test2(jedis);
//            test3(jedis);
//            test4(jedis);
            test5(jedis);
        }
    }

    private static void test5(Jedis jedis) {
        System.out.println("zrank");

        String key = createZSet(jedis);
        Long lisi = jedis.zrank(key, "lisi");
        System.out.println("lisi: " + lisi);
        System.out.println("qianqi: " + jedis.zrank(key, "qianqi"));
    }

    private static void test4(Jedis jedis) {
        System.out.println("zscore");

        // 时间复杂度是 O(1)
        String key = createZSet(jedis);
        // 返回是包装类 要考虑到没有的情况
        System.out.println("lisi: " + jedis.zscore(key, "lisi"));
        System.out.println("wangwu: " + jedis.zscore(key, "wangwu"));
        System.out.println("zhaoliu: " + jedis.zscore(key, "zhaoliu"));
        System.out.println("zhangsan: " + jedis.zscore(key, "zhangsan"));
    }

    private static void test3(Jedis jedis) {
        System.out.println("zrem");

        String key = createZSet(jedis);

        long count = jedis.zrem(key, "lisi", "zhangsan");
        System.out.println("result: " + count);

        List<Tuple> result = jedis.zrangeWithScores(key, 0, -1);
        System.out.println("result: " + result);

    }

    private static void test2(Jedis jedis) {
        System.out.println("zcard");

        String key = createZSet(jedis);
        System.out.println("result: " + jedis.zcard(key));
    }

    private static String createZSet(Jedis jedis) {
        String key = "k1";
        jedis.zadd(key, 10, "lisi");
        jedis.zadd(key, 20, "zhangsan");
        jedis.zadd(key, 30, "wangwu");
        return key;
    }

    private static void test1(Jedis jedis) {
        System.out.println("zadd and zrange");

        String key = createZSet(jedis);

        List<String> result = jedis.zrange(key, 0, -1);
        System.out.println("result: " + result);

        List<Tuple> resultWithScore = jedis.zrangeWithScores(key, 0, -1);
        System.out.println("resultWithScore: " + resultWithScore);

        double score = resultWithScore.get(0).getScore();
        String member = resultWithScore.get(0).getElement();
        System.out.println("member: " + member + " score: " + score);
    }
}
